//
//  WBQRCodeVC.m
//  SGQRCodeExample
//
//  Created by kingsic on 2018/2/8.
//  Copyright © 2018年 kingsic. All rights reserved.
//

#import "WBQRCodeVC.h"
#import "SGQRCode.h"
#import "ScanSuccessJumpVC.h"
#import "MBProgressHUD+SGQRCode.h"
#import "MyHelpCentreWebVC.h"
#import <AVFoundation/AVFoundation.h>


@interface WBQRCodeVC () {
    SGQRCodeObtain *obtain;
}
@property (nonatomic, strong) SGQRCodeScanView *scanView;
@property (nonatomic, strong) BaseLab *promptLabel;
@property (nonatomic, assign) BOOL stop;
@property (nonatomic, assign) BOOL turnTorchOn;//手电筒开关状态


@end

@implementation WBQRCodeVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (_stop) {
        [obtain startRunningWithBefore:nil completion:nil];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.scanView addTimer];
}

-(void)setNav{
        [self.baseNavigationView setHiddenNav:NO VC:self];

        /* TODO: ================= 导航栏V4样式 =================*/
        [self.baseNavigationView NavigationBarStyle:1];
        self.baseNavigationView.leftButton1.hidden = YES;
        self.baseNavigationView.isShowShadow = YES;
        self.baseNavigationView.navViewStyle.title.hidden = YES;
        self.baseNavigationView.navViewStyle.backgroundColor = [UIColor colorWithHex:@"333333"];
        self.baseNavigationView.navViewStyle.leftBtn.backgroundColor = [UIColor colorWithHex:@"333333"];
    
    
    
    
    UIImage *image = [UIImage imageNamed:@"common_back"];
    image =[image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [self.baseNavigationView.navViewStyle.rightBtn setImage:image forState:UIControlStateNormal];
    [self.baseNavigationView.navViewStyle.rightBtn.imageView setTintColor:[UIColor whiteColor]];
    
    // common_back
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.scanView removeTimer];
    self.turnTorchOn = NO;
    [self  turnTorchOn:self.turnTorchOn];
}

- (void)dealloc {
    NSLog(@"WBQRCodeVC - dealloc");
    [self removeScanningView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNav];

    self.view.backgroundColor = [UIColor blackColor];
    obtain = [SGQRCodeObtain QRCodeObtain];
    [self setupQRCodeScan];
    [self setupNavigationBar];
    [self.view addSubview:self.scanView];
    [self.view addSubview:self.promptLabel];
}

- (void)setupQRCodeScan {
    __weak typeof(self) weakSelf = self;

    SGQRCodeObtainConfigure *configure = [SGQRCodeObtainConfigure QRCodeObtainConfigure];
    configure.openLog = YES;
    configure.rectOfInterest = CGRectMake(0.05, 0.2, 0.7, 0.6);
    // 这里只是提供了几种作为参考（共：13）；需什么类型添加什么类型即可
    NSArray *arr = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    configure.metadataObjectTypes = arr;
    
    [obtain establishQRCodeObtainScanWithController:self configure:configure];
    [obtain startRunningWithBefore:^{
        [MBProgressHUD SG_showMBProgressHUDWithModifyStyleMessage:@"正在加载..." toView:weakSelf.view];
    } completion:^{
        [MBProgressHUD SG_hideHUDForView:weakSelf.view];
    }];
    @weakify(self);
    [obtain setBlockWithQRCodeObtainScanResult:^(SGQRCodeObtain *obtain, NSString *result) {
        @strongify(self);
        if (result) {
            [obtain stopRunning];
            weakSelf.stop = YES;
            [obtain playSoundName:@"SGQRCode.bundle/sound.caf"];
            
            
            if (self.block) {
                self.block(result);
            }
            [self.navigationController popViewControllerAnimated:YES];
//            MyHelpCentreWebVC * vc = [[MyHelpCentreWebVC alloc]init];
//            vc.title1 = @"二维码结果页面";
//            vc.url = result;
////            vc.url = @"http://appweb.test.cztec.com/#/share/ad";
//
////            ScanSuccessJumpVC *jumpVC = [[ScanSuccessJumpVC alloc] init];
////            jumpVC.comeFromVC = ScanSuccessJumpComeFromWB;
////            jumpVC.jump_URL = result;
//            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    }];
}

- (void)setupNavigationBar {
    self.navigationItem.title = @"扫一扫";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"相册" style:(UIBarButtonItemStyleDone) target:self action:@selector(rightBarButtonItenAction)];
}

- (void)rightBarButtonItenAction {
    __weak typeof(self) weakSelf = self;

    [obtain establishAuthorizationQRCodeObtainAlbumWithController:nil];
    if (obtain.isPHAuthorization == YES) {
        [self.scanView removeTimer];
    }
    [obtain setBlockWithQRCodeObtainAlbumDidCancelImagePickerController:^(SGQRCodeObtain *obtain) {
        [weakSelf.view addSubview:weakSelf.scanView];
    }];
    [obtain setBlockWithQRCodeObtainAlbumResult:^(SGQRCodeObtain *obtain, NSString *result) {
        if (result == nil) {
            NSLog(@"暂未识别出二维码");
        } else {
            if ([result hasPrefix:@"http"]) {
                ScanSuccessJumpVC *jumpVC = [[ScanSuccessJumpVC alloc] init];
                jumpVC.comeFromVC = ScanSuccessJumpComeFromWB;
                jumpVC.jump_URL = result;
                [weakSelf.navigationController pushViewController:jumpVC animated:YES];
                
            } else {
                ScanSuccessJumpVC *jumpVC = [[ScanSuccessJumpVC alloc] init];
                jumpVC.comeFromVC = ScanSuccessJumpComeFromWB;
                jumpVC.jump_bar_code = result;
                [weakSelf.navigationController pushViewController:jumpVC animated:YES];
            }
        }
    }];
}

- (SGQRCodeScanView *)scanView {
    if (!_scanView) {
        _scanView = [[SGQRCodeScanView alloc] initWithFrame:CGRectMake(0, NaviHeight, self.view.frame.size.width, self.view.frame.size.height-NaviHeight)];
        // 静态库加载 bundle 里面的资源使用 SGQRCode.bundle/QRCodeScanLineGrid
        // 动态库加载直接使用 QRCodeScanLineGrid
        
        _scanView.scanImageName = @"QRCodeScanLineGridD";
        _scanView.scanAnimationStyle = ScanAnimationStyleGrid;
        _scanView.cornerLocation = CornerLoactionOutside;
//        _scanView.cornerColor = [UIColor orangeColor];
        _scanView.cornerColor = baseColorTheme;

    }
    return _scanView;
}
- (void)removeScanningView {
    [self.scanView removeTimer];
    [self.scanView removeFromSuperview];
    self.scanView = nil;
}

- (BaseLab *)promptLabel {
    if (!_promptLabel) {
        _promptLabel = [[BaseLab alloc] init];
        _promptLabel.backgroundColor = [UIColor clearColor];
        CGFloat promptLabelX = 0;
        CGFloat promptLabelY = 0.73 * self.view.frame.size.height;
        CGFloat promptLabelW = self.view.frame.size.width;
        CGFloat promptLabelH = 25;
        _promptLabel.frame = CGRectMake(promptLabelX, promptLabelY, promptLabelW, promptLabelH);
        _promptLabel.textAlignment = NSTextAlignmentCenter;
        _promptLabel.font = [UIFont boldSystemFontOfSize:13.0];
        _promptLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.6];
        _promptLabel.text = @"点击打开手电筒";
        
        @weakify(self);
        [[_promptLabel addTag]subscribeNext:^(id  _Nullable x) {
            @strongify(self);
            NSLog(@"");
            self.turnTorchOn = !self.turnTorchOn;
            [self  turnTorchOn:self.turnTorchOn];
        }];
    }
    return _promptLabel;
}

-(void)turnTorchOn:(bool)on{

    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    
    if (captureDeviceClass !=nil) {
        
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch] && [device hasFlash]){
            [device lockForConfiguration:nil]; if (on) {
                
                [device setTorchMode:AVCaptureTorchModeOn];
                
                [device setFlashMode:AVCaptureFlashModeOn];
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
            } [device unlockForConfiguration];
        }else{
            
            NSLog(@"初始化失败");
        }
        
    }else{
        
        NSLog(@"没有闪光设备");
    }
    
}

@end
